<?php
/***************
对称加密解密基类
lsj 2010-12-11
***************/
if(!defined('APP_HOME')) exit('Access Denied');

class lib_class_mcrypt
{

	protected $mcrypt_key = 'NOmcryptKEY';
	protected $mcrypt_cipher = MCRYPT_RIJNDAEL_128;
	protected $mcrypt_mode = MCRYPT_MODE_ECB;

	function __construct($key = '')
	{
		$this->setKey($key);
		return true;
	}
	
	/*
	* 设置密钥
	*/
	public function setKey($key)
	{
		if($key != ''){
			$this->mcrypt_key = $key;
		}
		return $this;
	}
	
	/*
	* 设置加密算法
	*/
	public function setCipher($cipher)
	{
		$this->mcrypt_cipher = $cipher;
		return $this;
	}

	/*
	* 加密
	*/
	public function enCode($s)
	{
		if($s == '') return $s;
		$iv = $this->mcryptIV();
		$newString = mcrypt_encrypt($this->mcrypt_cipher, $this->mcrypt_key, $s, $this->mcrypt_mode, $iv);
		return bin2hex($newString);
	}

	/*
	* 解密 
	*/
	public function deCode($s)
	{
		if($s == '') return $s;
		$iv = $this->mcryptIV();
		$s = @pack("H*", $s);
		$newString = mcrypt_decrypt($this->mcrypt_cipher, $this->mcrypt_key, $s, $this->mcrypt_mode, $iv);
		return trim($newString);
	}
	
	/*
	* 产生自变量
	*/
	public function mcryptIV()
	{
		$size = mcrypt_get_iv_size($this->mcrypt_cipher, $this->mcrypt_mode);
		$iv = mcrypt_create_iv($size, MCRYPT_RAND);
		return $iv;
	}
	
}

?>